package com.ruoyi.project.mobile.cart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.R;
import com.ruoyi.common.utils.RFactory;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.goods.cart.domain.ShoppingCart;
import com.ruoyi.project.system.goods.cart.dto.CartDto;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.fee.domain.GoodsPostFee;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.goods.domain.GoodsDto;
import com.ruoyi.project.system.goods.goods.enums.GoodsTag;
import com.ruoyi.project.system.goods.goods.service.IGoodsGoodsService;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.service.IMemberService;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/27 21:58
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/cart")
public class ApiShopCartController extends BaseController {

	@Autowired
	private IShoppingCartService shoppingCartService;

	@Autowired
	private IMemberAddressService memberAddressService;

	@Autowired
	private IGoodsProductService goodsProductService;

	@Autowired
	private IGoodsGoodsService goodsGoodsService;

	@Autowired
	private IMemberService memberService;

	@Autowired
	private IGoodsPostFeeService goodsPostFeeService;

	/**
	 * 查询购物车列表
	 * @param uid
	 * @return
	 */
	@GetMapping
	public R userCart(@RequestParam String uid){
		startPage();
		List<CartDto> cartDtoList = this.shoppingCartService.findListByUid(uid);
		return RFactory.generateR(getDataTable(cartDtoList));
	}

	/**
	 * 修改购物车商品数量
	 * @param map
	 * @return
	 */
	@PutMapping("/update")
	public R updateCart(@RequestBody Map map){
		String uid = (String) map.get("uid");
		int total = (int) map.get("total");
		String id = (String) map.get("id");
		ShoppingCart shoppingCart = new ShoppingCart();
		shoppingCart.setId(id);
		shoppingCart.setTotal(Integer.toUnsignedLong(total));
		this.shoppingCartService.updateShoppingCart(shoppingCart);
		return R.ok();
	}

	/**
	 * 删除购物车
	 * @param map
	 * @return
	 */
	@DeleteMapping
	public R deleteCart(@RequestBody Map map){
		String uid = (String) map.get("uid");
		ArrayList ids = (ArrayList) map.get("ids");
		this.shoppingCartService.deleteShoppingCartByIds(ids);
		return R.ok();
	}

	/**
	 * 准备下单
	 * @param uid
	 * @param cartIds
	 * @return
	 */
	@GetMapping("/ready")
	public R cartOrder(@RequestParam String uid,@RequestParam String[] cartIds){
		if(cartIds.length==0){
			return R.error("请至少一件商品");
		}
		HashMap<String, Object> map = new HashMap<>();
		//查询默认地址信息
		MemberAddress memberAddress = this.memberAddressService.findDefault(uid);
		map.put("address",memberAddress);
		//默认审核通过
		map.put("examine",0);
		//查询商品信息
		BigDecimal sumGoodsPrice = new BigDecimal(0);
		BigDecimal sumPostFee = new BigDecimal(0);
		int goodsCount = 0;
		ArrayList<GoodsDto> goodsDtos = new ArrayList<>();
		Member member = this.memberService.selectMemberById(uid);
		for(int i=0;i<cartIds.length;i++){
			ShoppingCart shoppingCart = this.shoppingCartService.selectShoppingCartById(cartIds[i]);
			if(shoppingCart==null){
				break;
			}
			GoodsDto goodsDto = this.goodsGoodsService.findGoodsDtoByPId(shoppingCart.getProductId());
			//如果商品是秒杀商品
			if(goodsDto.getHasSpike()==1){
				//判断是否在秒杀期间
				if(goodsDto.getSpikeStart().getTime()>DateUtils.getNowDate().getTime()||goodsDto.getSpikeEnd().getTime()<DateUtils.getNowDate().getTime()){
					return R.error("商品:"+goodsDto.getName()+" 不在秒杀时间 不可购买");
				}
			}

			goodsDto.setTotal(shoppingCart.getTotal().intValue());
			goodsDto.setSpecId(shoppingCart.getProductId());
			goodsDtos.add(goodsDto);
			if(member.getIsVip().equals(MemberIsVip.YES.getValue())){
				sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceVip().multiply(new BigDecimal(shoppingCart.getTotal())));
			}else{
				sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceN().multiply(new BigDecimal(shoppingCart.getTotal())));
			}
			// 获取该地区的运费
			List<GoodsPostFee> goodsPostFeeList = this.goodsPostFeeService.findListByGoodsId(goodsDto.getId());
			for(GoodsPostFee goodsPostFee :goodsPostFeeList){
				if(memberAddress.getArea().indexOf(goodsPostFee.getName())!=-1){
					goodsDto.setPostFee(goodsPostFee.getPostFee());
					break;
				}
			}
			sumPostFee=sumPostFee.add(goodsDto.getPostFee());
			goodsCount=goodsCount+shoppingCart.getTotal().intValue();
			//判断商品是否是认证
			if(!goodsDto.getTag().equals(GoodsTag.QUALITY_GOODS.getValue())){
				//判断当前用户是否已认证
				if(!member.getIsExamine().equals(2)){
					map.put("examine",1);
				}
			}
		}
		map.put("sumPostFee",sumPostFee);
		map.put("sumGoodsPrice",sumGoodsPrice);
		map.put("sumPrice",sumGoodsPrice.add(sumPostFee));
		map.put("goods",goodsDtos);
		map.put("goodsCount",goodsCount);
		map.put("cartIds",cartIds);
		return RFactory.generateR(map);
	}


	/**
	 * 检车购物车准备下单的商品是否存在不可购买的
	 * @param uid
	 * @param cartIds
	 * @return
	 */
	@GetMapping("/checks")
	public R checks(@RequestParam String uid,@RequestParam String[] cartIds){
		if(cartIds.length==0){
			return R.error("请至少一件商品");
		}
		for(int i=0;i<cartIds.length;i++) {
			ShoppingCart shoppingCart = this.shoppingCartService.selectShoppingCartById(cartIds[i]);
			if (shoppingCart == null) {
				break;
			}
			GoodsDto goodsDto = this.goodsGoodsService.findGoodsDtoByPId(shoppingCart.getProductId());
			//如果商品是秒杀商品
			if (goodsDto.getHasSpike() == 1) {
				//判断是否在秒杀期间
				if (goodsDto.getSpikeStart().getTime() > DateUtils.getNowDate().getTime() || goodsDto.getSpikeEnd().getTime() < DateUtils.getNowDate().getTime()) {
					return R.error("商品:" + goodsDto.getName() + " 不在秒杀时间 不可购买");
				}
			}
		}
		return R.ok();
	}

}
